package com.huhao.wshare;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.huhao.wshare.Config.LOGIN_API;

public class LoginActivity extends BaseActivity {

    private TextInputEditText etAccount;
    private TextInputEditText etPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 检查 SharedPreferences 中的 token
        SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String token = sp.getString("token", null);
        int id = sp.getInt("id", -1);

        if (token != null && id != -1) {
            // token 和 id 存在，跳转到主界面
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        // token 不存在，正常加载登录界面
        setContentView(R.layout.activity_login);

        etAccount = findViewById(R.id.et_account);
        etPassword = findViewById(R.id.et_password);
        MaterialButton btnLogin = findViewById(R.id.btn_login);

        btnLogin.setOnClickListener(v -> {
            String identifier = etAccount.getText().toString().trim();
            String password = etPassword.getText().toString().trim();

            if (identifier.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "请输入账号和密码", Toast.LENGTH_SHORT).show();
                return;
            }
            doLogin(identifier, password);
        });

        // 跳转注册页
        TextView tvGoRegister = findViewById(R.id.tv_go_register);
        tvGoRegister.setOnClickListener(v ->
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class)));
    }

    private void doLogin(String identifier, String password) {
        JSONObject json = new JSONObject();
        try {
            json.put("identifier", identifier);
            json.put("password", password);
        } catch (JSONException e) {
            Log.e("Login", "构建 JSON 失败", e);
            return;
        }

        RequestBody body = RequestBody.create(json.toString(),
                MediaType.get("application/json; charset=utf-8"));

        Request request = new Request.Builder()
                .url(LOGIN_API)
                .post(body)
                .build();

        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() ->
                        Toast.makeText(LoginActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String respStr = response.body().string();
                runOnUiThread(() -> handleLoginResponse(response.code(), respStr));
            }
        });
    }

    private void handleLoginResponse(int code, String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);

            if (code == 200) {
                // 登录成功
                String token = json.optString("token");
                int id = json.optInt("id");
                saveTokenAndId(token, id);
                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, MainActivity.class));
                finish();
                return;
            }

            StringBuilder msg = new StringBuilder();

            if (code == 400) {
                // 参数校验失败
                if (json.has("errors")) {
                    JSONObject errors = json.getJSONObject("errors");
                    if (errors.has("identifier"))
                        msg.append(errors.optString("identifier")).append("\n");
                    if (errors.has("password"))
                        msg.append(errors.optString("password"));
                } else {
                    // 重复登录
                    msg.append(json.optString("message"));
                }
            } else if (code == 401) {
                // 认证失败
                msg.append(json.optString("message"));
            } else {
                msg.append("未知错误");
            }

            Toast.makeText(this, msg.toString().trim(), Toast.LENGTH_SHORT).show();

        } catch (JSONException e) {
            Toast.makeText(this, "解析响应失败", Toast.LENGTH_SHORT).show();
            Log.e("Login", "解析 JSON 失败", e);
        }
    }

    private void saveTokenAndId(String token, int id) {
        SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
        sp.edit()
                .putString("token", token)
                .putInt("id", id)
                .apply();
        Log.i("token", token);
    }
}